package com.yunwaikeji.gy_tool_library.utils.file;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;

import androidx.core.content.FileProvider;

import com.yunwaikeji.gy_tool_library.base.GYBaseUtils;
import com.yunwaikeji.gy_tool_library.info.GYFileInfo;
import com.yunwaikeji.gy_tool_library.utils.file.copy.GYFileCopyBuilder;
import com.yunwaikeji.gy_tool_library.utils.file.delete.GYFileDeleteTask;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件工具类
 */
public class GYFileUtils extends GYBaseUtils implements GYFileInfo {
    public static GYFileDeleteTask newFileDeleteTask() {
        return new GYFileDeleteTask();
    }

    public static GYFileDeleteTask newFileDeleteTask(File file) {
        return new GYFileDeleteTask(file);
    }

    public static GYFileDeleteTask newFileDeleteTask(String file) {
        return new GYFileDeleteTask(file);
    }

    public static boolean hasFile(File file) {
        return getFiles(file, FileType.FILE).size() != 0;
    }

    public static boolean hasDirectory(File file) {
        return getFiles(file, FileType.DIRECTORY).size() != 0;
    }

    public static boolean hasAll(File file) {
        return getFiles(file).size() != 0;
    }

    public static List<File> getFiles(File file) {
        return getFiles(file, FileType.ALL);
    }

    //获取文件或文件夹
    public static List<File> getFiles(File file, FileType fileType) {
        List<File> fileList = new ArrayList<>();
        if (file.exists()) {
            if (file.isFile()) {
                if (fileType == FileType.FILE || fileType == FileType.ALL) {
                    fileList.add(file);
                }
            } else if (file.isDirectory()) {
                File[] files = file.listFiles();
                if (files != null) {
                    for (File file1 : files) {
                        fileList.addAll(getFiles(file1, fileType));
                    }
                }
                if (fileType == FileType.DIRECTORY || fileType == FileType.ALL) {
                    fileList.add(file);
                }
            }
        }
        return fileList;
    }

    /**
     * 获取文件/文件夹大小
     *
     * @param filePath
     * @return
     */
    public static Long getSize(File filePath) {
        long size = 0;
        if (filePath.exists()) {
            if (filePath.isFile()) {
                size += filePath.length();
            } else if (filePath.isDirectory()) {
                File[] files = filePath.listFiles();
                if (files.length > 0) {
                    for (File file : files) {
                        size += getSize(file);
                    }
                }
            }
        }
        return size;
    }

    public static String getFormatSize(double size) {
        return getFormatSize(size, 2);
    }

    /**
     * 格式化单位
     *
     * @param size
     * @return
     */
    public static String getFormatSize(double size, int newScale) {
        if (size == 0) {
            return "0B";
        }
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            BigDecimal result = new BigDecimal(Double.toString(size));
            return result.setScale(newScale, BigDecimal.ROUND_HALF_UP) + "B";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(newScale, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(newScale, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(newScale, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(newScale, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }

    public static String getName(String filePath) {
//        String fileName = "";
//        if (!TextUtils.isEmpty(filePath)) {
//            String[] strings = filePath.split(File.separator);
//            fileName = strings[strings.length - 1];
//        }
        return new File(filePath).getName();
    }

    public static String getNameByPrefix(String filePath) {
        return getName(filePath).split("[.]")[0];
    }

    public static String getNameBySuffix(String filePath) {
        String[] names = getName(filePath).split("[.]");
        if (names.length >= 2) {
            return names[1];
        }
        return "";
    }

    public static Intent getFileIntent(Context context, String authority, String filePath) {
        return getFileIntent(context, authority, new File(filePath));
    }

    public static Intent getFileIntent(Context context, String authority, File file) {
        if (!file.exists()) {
            return null;
        }
        /* 取得扩展名 */
        String end = file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase();
        /* 依扩展名的类型决定MimeType */
        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") ||
                end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            return getAudioFileIntent(context, authority, file);
        } else if (end.equals("3gp") || end.equals("mp4")) {
            return getAudioFileIntent(context, authority, file);
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png") ||
                end.equals("jpeg") || end.equals("bmp")) {
            return getImageFileIntent(context, authority, file);
        } else if (end.equals("apk")) {
            return getApkFileIntent(context, authority, file);
        } else if (end.equals("ppt")) {
            return getPptFileIntent(context, authority, file);
        } else if (end.equals("xls")) {
            return getExcelFileIntent(context, authority, file);
        } else if (end.equals("doc")) {
            return getWordFileIntent(context, authority, file);
        } else if (end.equals("pdf")) {
            return getPdfFileIntent(context, authority, file);
        } else if (end.equals("chm")) {
            return getChmFileIntent(context, authority, file);
        } else if (end.equals("txt")) {
            return getTextFileIntent(context, authority, file, false);
        } else {
            return getAllIntent(context, authority, file);
        }
    }

    private static Intent newIntent() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
        return intent;
    }

    //Android获取一个用于打开所有文件的intent
    public static Intent getAllIntent(Context context, String authority, File file) {
        Intent intent = newIntent();
        intent.setDataAndType(getUri(context, authority, file), "*/*");
        return intent;
    }

    //Android获取一个用于打开APK文件的intent
    public static Intent getApkFileIntent(Context context, String authority, File file) {
        Intent intent = newIntent();
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(getUri(context, authority, file), "application/vnd.android.package-archive");
        return intent;
    }

    //Android获取一个用于打开VIDEO文件的intent
    public static Intent getVideoFileIntent(Context context, String authority, File file) {
        Intent intent = newIntent();
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("oneshot", 0);
        intent.putExtra("configchange", 0);
        intent.setDataAndType(getUri(context, authority, file), "video/*");
        return intent;
    }

    //Android获取一个用于打开AUDIO文件的intent
    public static Intent getAudioFileIntent(Context context, String authority, File file) {
        Intent intent = newIntent();
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("oneshot", 0);
        intent.putExtra("configchange", 0);
        intent.setDataAndType(getUri(context, authority, file), "audio/*");
        return intent;
    }

    //Android获取一个用于打开Html文件的intent
    public static Intent getHtmlFileIntent(Context context, String authority, File file) {
        Uri uri = Uri.parse(file.getPath()).buildUpon().encodedAuthority("com.android.htmlfileprovider").scheme("content").encodedPath(file.getPath()).build();
        Intent intent = newIntent();
        intent.setDataAndType(uri, "text/html");
        return intent;
    }

    //Android获取一个用于打开图片文件的intent
    public static Intent getImageFileIntent(Context context, String authority, File file) {
        Intent intent = newIntent();
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(getUri(context, authority, file), "image/*");
        return intent;
    }

    //Android获取一个用于打开PPT文件的intent
    public static Intent getPptFileIntent(Context context, String authority, File file) {
        Intent intent = newIntent();
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(getUri(context, authority, file), "application/vnd.ms-powerpoint");
        return intent;
    }

    //Android获取一个用于打开Excel文件的intent
    public static Intent getExcelFileIntent(Context context, String authority, File file) {
        Intent intent = newIntent();
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(getUri(context, authority, file), "application/vnd.ms-excel");
        return intent;
    }

    //Android获取一个用于打开Word文件的intent
    public static Intent getWordFileIntent(Context context, String authority, File file) {
        Intent intent = newIntent();
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(getUri(context, authority, file), "application/msword");
        return intent;
    }

    //Android获取一个用于打开CHM文件的intent
    public static Intent getChmFileIntent(Context context, String authority, File file) {
        Intent intent = newIntent();
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(getUri(context, authority, file), "application/x-chm");
        return intent;
    }

    //Android获取一个用于打开文本文件的intent
    public static Intent getTextFileIntent(Context context, String authority, File file, boolean paramBoolean) {
        Intent intent = newIntent();
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (paramBoolean) {
            Uri uri1 = Uri.parse(file.getPath());
            intent.setDataAndType(uri1, "text/plain");
        } else {
            Uri uri2 = Uri.fromFile(file);
            intent.setDataAndType(uri2, "text/plain");
        }
        return intent;
    }

    //Android获取一个用于打开PDF文件的intent
    public static Intent getPdfFileIntent(Context context, String authority, File file) {
        Intent intent = newIntent();
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(getUri(context, authority, file), "application/pdf");
        return intent;
    }

    public static Uri getUri(Context context, String authority, File file) {
        Uri uri;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            uri = Uri.fromFile(file);
        } else {
            uri = FileProvider.getUriForFile(context, authority, file);
        }
        return uri;
    }

    public static String getPathByChildPaths(String... childPaths) {
        String path = "";
        for (String directory : childPaths) {
            if (!TextUtils.isEmpty(path)) {
                path += File.separator;
            }
            path += directory;
        }
        return path;
    }

    public static String getPath(String path) {
        if (!TextUtils.isEmpty(path)) {
            String result = "";
            for (String child : path.split(File.separator)) {
                if (!TextUtils.isEmpty(child)) {
                    if (!TextUtils.isEmpty(result)) {
                        result += File.separator;
                    }
                    result += child;
                }
            }
            return result;
        }
        return path;
    }

    //获取文件夹路径
    public static String getDirectoryPath(String path) {
        String[] strings = getPath(path).split(File.separator);
        if (isFileName(strings[strings.length - 1])) {
            String result = "";
            for (int i = 0; i < strings.length - 1; i++) {
                if (!TextUtils.isEmpty(result)) {
                    result += File.separator;
                }
                result += strings[i];
            }
            return result;
        }
        return path;
    }

    //获取文件夹路径
    public static String getDirectoryPath(File file) {
        return getDirectoryPath(file.getPath());
    }

    //获取文件名
    public static String getFileName(String path) {
        String[] strings = getPath(path).split(File.separator);
        String last = strings[strings.length - 1];
        if (isFileName(last)) {
            return last;
        }
        return "";
    }

    //获取文件名
    public static String getFileName(File file) {
        return getFileName(file.getPath());
    }

    //是否是文件名
    public static boolean isFileName(String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            return false;
        }
        if (fileName.contains(File.separator)) {
            return false;
        }
        if (fileName.split("[.]").length != 2) {
            return false;
        }
        if (fileName.indexOf("\\.") == 0) {
            return false;
        }
        if (fileName.indexOf("\\.") == fileName.length() - 1) {
            return false;
        }
        return true;
    }

    public static GYFileCopyBuilder newCopyBuilder() {
        return new GYFileCopyBuilder();
    }

    public static GYFileCopyBuilder newCopyBuilder(File oldFile, File newFile) {
        return new GYFileCopyBuilder(oldFile, newFile);
    }

    public static GYFileCopyBuilder newCopyBuilder(String oldFile, String newFile) {
        return new GYFileCopyBuilder(oldFile, newFile);
    }

    public static GYFileWriteTask newFileWriteTask() {
        return new GYFileWriteTask();
    }

    /**
     * 读取assets下的文件
     *
     * @param context
     * @param fileName 不包括后缀
     * @return
     */
    public static String readAssets(Context context, String fileName, Charset charset) {
        try {
            //Return an AssetManager instance for your application's package
            InputStream inputStream = context.getAssets().open(fileName);
            int size = inputStream.available();
            // Read the entire asset into a local byte buffer.
            byte[] buffer = new byte[size];
            inputStream.read(buffer);
            inputStream.close();
            // Convert the buffer into a string.
            // Finally stick the string into the text view.
            return new String(buffer, charset);
        } catch (IOException e) {
            // Should never happen!
//            throw new RuntimeException(e);
            e.printStackTrace();
        }
        return "[读取失败]";
    }

    public static String readAssets(Context context, String fileName) {
        return readAssets(context, fileName, StandardCharsets.UTF_8);
    }
}
